package com.zzyy.study.controller;

import com.fasterxml.jackson.databind.JsonNode;
import io.github.pigmesh.ai.deepseek.core.DeepSeekClient;
import io.github.pigmesh.ai.deepseek.core.chat.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @auther zzyy
 * @create 2025-02-15 23:24
 */
@RestController
@Slf4j
public class DeepSeekController
{
    @Resource
    private DeepSeekClient deepSeekClient;

    /**http://localhost:9000/deepseek/chat?prompt=你是谁
     * 同步输出 （非实时响应流）
     * 不推荐使用同步阻塞调用方式，R1模型推理耗时较长易导致客户端连接超时，且响应延迟会影响用户体验
     * @param prompt
     * @return
     */
    @CrossOrigin("*")
    @GetMapping(value = "/deepseek/chat")
    public String chat(@RequestParam("prompt") String prompt) {
        ChatCompletionRequest request = ChatCompletionRequest.builder().addUserMessage(prompt).build();

        long startTime = System.currentTimeMillis();
        ChatCompletionResponse result = deepSeekClient.chatCompletion(request).execute();
        long endTime = System.currentTimeMillis();
        System.out.println("----costTime: "+(endTime - startTime) +" 毫秒");

        return result.content();
    }

    /**SSE服务器推送事件数据流
     * https://apifox.pkfare.com/help/debugging-api/sse/
     *
     * SSE（Server-Sent Events）的全称是服务器推送事件，它是一种基于 HTTP 协议的实时通信技术，
     * 用于在客户端和服务器之间建立持久、单向的链接，允许服务器向客户端发送异步消息
     * @param prompt
     *
     * http://localhost:9000/sse2.html
     * @return
     */
    @CrossOrigin("*")
    @GetMapping(value = "/deepseek/chat3", produces = MediaType.TEXT_EVENT_STREAM_VALUE+ ";charset=UTF-8")
    public Flux<ChatCompletionResponse> chat3(@RequestParam("prompt") String prompt, HttpServletResponse response) {
        // 设置响应的字符编码
        response.setCharacterEncoding("UTF-8");

        return deepSeekClient.chatFluxCompletion(prompt);
    }

    @GetMapping(value = "/deepseek/chat4", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ChatCompletionResponse> chatAdvanced(@RequestParam("prompt") String prompt)
    {
        ChatCompletionRequest request = ChatCompletionRequest.builder()
                // 添加用户消息
                .addUserMessage(prompt)
                // 添加助手消息，用于多轮对话
                .addAssistantMessage("上轮结果")
                // 添加系统消息，用于设置角色和行为
                .addSystemMessage("你是一个专业的助手")
                // 设置最大生成 token 数，默认 2048
                .maxTokens(1000)
                .build();

        return deepSeekClient.chatFluxCompletion(request);
    }
}
